<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Lazy Load Images</title>
    <style>
      .lazy {
        width: 100%;
        height: 200px;
        background-color: #f3f3f3;
      }
    </style>
  </head>
  <body>
    <img class="lazy" data-src="image1.jpg" alt="Image 1" />
    <img class="lazy" data-src="image2.jpg" alt="Image 2" />
    <img class="lazy" data-src="image3.jpg" alt="Image 3" />
    <script>
      document.addEventListener("DOMContentLoaded", function () {
        const lazyImages = document.querySelectorAll("img.lazy");

        const lazyLoad = () => {
          lazyImages.forEach((img) => {
            if (
              img.getBoundingClientRect().top < window.innerHeight &&
              img.getBoundingClientRect().bottom > 0 &&
              getComputedStyle(img).display !== "none"
            ) {
              img.src = img.dataset.src;
              img.classList.remove("lazy");
            }
          });

          if (lazyImages.length === 0) {
            document.removeEventListener("scroll", lazyLoad);
            window.removeEventListener("resize", lazyLoad);
            window.removeEventListener("orientationchange", lazyLoad);
          }
        };

        document.addEventListener("scroll", lazyLoad);
        window.addEventListener("resize", lazyLoad);
        window.addEventListener("orientationchange", lazyLoad);
        lazyLoad(); // 初始化时检查一次
      });
    </script>
  </body>
</html>
